package com.jblog.controller.directive.abs;

import static com.jblog.common.web.FrontUtils.PARAM_PAGE_CSS_CLASS;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.jblog.common.web.FrontUtils;
import com.jblog.common.web.freemarker.DirectiveUtils;
import com.jblog.core.model.blog.Post;
import com.jblog.core.model.blog.param.CommentParam;
import com.jblog.core.service.facde.BlogFacade;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public abstract class AbstractCommentDirective implements
        TemplateDirectiveModel {
    
    protected abstract boolean isPage();
    
    @Autowired protected BlogFacade iblog; 

    public static final String PARAM_POST_ID  =  "postId";

    protected Long postId(Map<String, TemplateModel> params) throws TemplateException {
        return DirectiveUtils.getLong(PARAM_POST_ID, params);
    }
    
    protected String cssClass(Map<String, TemplateModel> params) throws TemplateException {
        return DirectiveUtils.getString(PARAM_PAGE_CSS_CLASS, params);
    }

    protected Object getData(Map<String, TemplateModel> params, Environment env)
            throws TemplateException {
        
        CommentParam cmtParam;
        if (isPage()) {
            cmtParam = new CommentParam(FrontUtils.start(params, env), FrontUtils.end(params, env));
        } else {
            cmtParam = new CommentParam(FrontUtils.first(params), FrontUtils.count(params));
        }
        cmtParam.setPost(new Post(postId(params)));
        cmtParam.setPageNo(FrontUtils.pageNo(env));
        cmtParam.setPageSize(FrontUtils.count(params));
        cmtParam.setCssClass(cssClass(params));
        
        if (isPage()) {
            return iblog.findCommentByParamByPage(cmtParam);
        } else {
            return iblog.findCommentByParam(cmtParam);
        }
        
    }
}
